<template>
  <div class="evaluateAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button" v-if="!contactAddShow && pageType !== 'detail'">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="submitForm()"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn back" @click="handleBack()"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="!contactAddShow && pageType !== 'detail'"
        :class="contactAddShow ? 'customInfoUpClass' : 'customInfoDownClass'"
      >
        <template #title>
          <span class="circle"></span>
          <span style="font-weight: bold">基本信息</span>
        </template>
        <div class="evaluate-info">
          <el-form :model="form" label-width="80px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="角色名称">
                  <el-input v-model="form.roleName" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="权限字符">
                  <el-input v-model="form.roleKey" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="权限范围">
                  <el-select
                    ref="refInput"
                    style="width: 100%"
                    v-model="form.dataScope"
                    @change="dataScopeSelectChange"
                  >
                    <el-option
                      v-for="item in dataScopeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="数据权限" v-show="form.dataScope == 2">
              <el-checkbox
                v-model="deptExpand"
                @change="handleCheckedTreeExpand($event, 'dept')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="deptNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'dept')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox
                v-model="form.deptCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'dept')"
                >父子联动</el-checkbox
              >
              <el-tree
                class="tree-border"
                :data="deptOptions"
                show-checkbox
                default-expand-all
                ref="deptRef"
                node-key="id"
                :check-strictly="!form.deptCheckStrictly"
                empty-text="加载中，请稍候"
                :props="{ label: 'label', children: 'children' }"
              ></el-tree>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { dataScope, getRole, deptTreeSelect } from "@/api/system/role";
import { getAuthRole, updateAuthRole } from "@/api/system/user";
const emit = defineEmits(["refreshList", "update:dataAddShow"]);
const props = defineProps({
  pageType: {
    type: String,
    default: "add",
  },
});

const { proxy } = getCurrentInstance();
const deptOptions = ref([]);
const form = ref({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: "0",
  menuIds: [],
  deptIds: [],
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: undefined,
});
const activeNames = ref(["1", "2"]);
const detailInfoShow = ref(false);
const contactAddShow = ref(false);
const deptRef = ref(null);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const refInput = ref(null);
/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
  { value: "6", label: "本公司数据权限" },
  { value: "4", label: "本部门及以下数据权限" },
  { value: "3", label: "本部门数据权限" },
  { value: "5", label: "仅本人数据权限" },
]);

const handleBack = () => {
  emit("update:dataAddShow", false);
  emit("refreshList", true);
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: "0",
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined,
  };
};
/** 提交按钮 */
function submitForm() {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      emit("update:dataAddShow", false);
      emit("refreshList", true);
    });
  }
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys();
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

// 处理详情信息
const handleDetailInfo = async (roleId) => {
  try {
    detailInfoShow.value = true;
    const deptTreeSelect = getDeptTree(roleId);
    getRole(roleId).then((response) => {
      form.value = response.data;
      nextTick(() => {
        deptTreeSelect.then((res) => {
          nextTick(() => {
            if (deptRef.value) {
              deptRef.value.setCheckedKeys(res.checkedKeys);
            }
          });
        });
      });
      detailInfoShow.value = false;
    });
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([]);
  }
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "dept") {
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else if (type == "dept") {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    form.value.deptCheckStrictly = value ? true : false;
  }
}

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then((response) => {
    deptOptions.value = response.depts;
    return response;
  });
}

onMounted(() => {
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}
.evaluateAdd {
  padding: 20px 30px;
  width: 100%;
  height: 100%;
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  /* .search-button {
    position: fixed;
    top: 110px;
    right: 60px;
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 34px;
      padding: 10px;
      // margin-right: 20px;
      font-size: 14px;
      border-radius: 4px;
      user-select: none;
      cursor: pointer;
    }
    .btn.save {
      color: #fff;
      background: rgba(67, 207, 124, 1);
      border: none;
      &:hover {
        background: rgba(67, 207, 124, 0.85);
      }
    }

    .btn.add {
      color: #fff;
      background: rgba(0, 124, 239, 1);
      &:hover {
        background: rgba(0, 124, 239, 0.85);
      }
    }

    .btn.back {
      border: none;
      color: #fff;
      background: rgba(255, 159, 0, 1);
      &:hover {
        background: rgba(255, 159, 0, 0.85);
      }
    }
    .btn.direction {
      border: none;
      color: #fff;
      background: rgba(153, 153, 153, 1);
      &:hover {
        background: rgba(153, 153, 153, 0.85);
      }
    }

    .icon {
      margin-right: 6px;
    }
  } */
  .circle {
    margin: 0 10px 0 20px;
    width: 6px;
    height: 6px;
    background: #007cef;
    border-radius: 50%;
  }
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .evaluate-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }

  .button-position {
    top: 6px;
    right: 30px;
  }
  :deep(.el-input__inner) {
    height: 34px;
  }
  .customInfoUpClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }
  .customInfoDownClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }

  .contactInfoUpClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  .contactInfoDownClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  @-webkit-keyframes customInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes customInfoDown {
    0% {
      opacity: 0;
      -webkit-transform: translateY(-80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes contactInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  .pagination {
    margin: 20px auto;
  }
}
</style>
